package DesignPattern.prototype;

/**
 * @Author cj
 * @Date 2024/8/10 20:48
 */
public class deepClone {
}

class CurrentAddress implements Cloneable {
    String city;

    public CurrentAddress(String city) {
        this.city = city;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 深拷贝CurrentAddress
    }
}

class OnePerson implements Cloneable {
    String name;
    CurrentAddress currentAddress;

    public OnePerson(String name, CurrentAddress currentAddress) {
        this.name = name;
        this.currentAddress = currentAddress;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 先浅拷贝OnePerson对象
        OnePerson cloned = (OnePerson) super.clone();
        // 深拷贝CurrentAddress对象
        cloned.currentAddress = (CurrentAddress) currentAddress.clone();
        return cloned;
    }

    @Override
    public String toString() {
        return name + " lives in " + currentAddress.city;
    }

    public static void main(String[] args) {
        try {
            CurrentAddress CurrentAddress = new CurrentAddress("New York");
            OnePerson original = new OnePerson("John", CurrentAddress);
            OnePerson copy = (OnePerson) original.clone();

            copy.name = "Doe";
            copy.currentAddress.city = "San Francisco";

            System.out.println(original); // 输出: John lives in New York
            System.out.println(copy);     // 输出: Doe lives in San Francisco
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
